package com.ck.hutool;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DataExcelExportDemo {

    public static void main(String[] args) {
        //System.out.println(getMobileInfo("13242967410"));

        File file = new File("E:\\temp\\kdy.xlsx");
        ExcelReader reader = ExcelUtil.getReader(file,0);
        //根据指定行开始读取所有的内容
        List<List<Object>> rows = reader.read();
        List<List<?>> writeExcelRows = new ArrayList<>();
        for(List<Object> list:rows){
            Map<String, Object> mobileInfo = getMobileInfo(list.get(0).toString());
            List<?> row = CollUtil.newArrayList(list.get(0),list.get(1),list.get(2),list.get(3),list.get(4),list.get(5),mobileInfo.get("prov"),mobileInfo.get("city"),mobileInfo.get("types"));
            writeExcelRows.add(row);
        }
        //在获取到所有的数据后，要关闭reader(切记)，操作文件总是失败，最后才发现在service调用没有关闭流，粗心大意了！
        reader.close();
        writeExcel(writeExcelRows);
    }


    public static void writeExcel(List<List<?>> rows){
        BigExcelWriter writer= ExcelUtil.getBigWriter("E:\\temp\\666.xlsx");
        // 一次性写出内容，使用默认样式
        writer.write(rows);
        // 关闭writer，释放内存
        writer.close();
    }

    /**
     * 调用阿里云接口-获取手机运营商
     * 地址: https://market.aliyun.com/products/57126001/cmapi022206.html?spm=5176.2020520132.101.3.47837218a7YSJb#sku=yuncode1620600000
     * @param mobile
     * @return
     */
    private static Map<String,Object> getMobileInfo(String mobile){
        String host = "https://api04.aliyun.venuscn.com";
        String path = "/mobile";
        String appcode = "52d6ab05212e46f4b92482fe4fd2ffbc";
        Map<String,Object> dataMap = null;
        String results = HttpRequest.get(host + path)
                .header("Authorization", "APPCODE " + appcode)
                .form("mobile", mobile)
                .execute().body();
        Map<String,Object> map = JSONUtil.toBean(results, HashMap.class);
        if("200".equals(map.get("ret").toString())){
            dataMap = JSONUtil.toBean(map.get("data").toString(), HashMap.class);
        }
        return dataMap;
    }

}
